<template>
  <div class="problem-comments">
    <!-- 讨论内容 -->
    <div class="discussion-content" v-loading="loading">
      <div class="discussion-header">
        <h1>{{ discussion.title }}</h1>
        <div class="discussion-meta">
          <div class="user-info">
            <el-avatar :src="discussion.avatar || defaultAvatar" :size="40"></el-avatar>
            <div class="author-info">
              <span class="author-name">{{ discussion.author }}</span>
              <span class="role-tag" v-if="discussion.role === 1">教师</span>
              <span class="role-tag" v-else-if="discussion.role === 2">管理员</span>
              <span class="create-time">{{ formatTime(discussion.createTime) }}</span>
            </div>
          </div>
          <div class="action-buttons" v-if="isLoggedIn">
            <el-button
              :type="isLiked ? 'primary' : 'default'"
              :icon="isLiked ? 'StarFilled' : 'Star'"
              @click="handleLike"
            >
              {{ discussion.likeNum || 0 }}
            </el-button>
            <el-button
              :type="isCollected ? 'primary' : 'default'"
              :icon="isCollected ? 'Collection' : 'Collection'"
              @click="handleCollect"
            >
              {{ isCollected ? '已收藏' : '收藏' }}
            </el-button>
          </div>
        </div>
      </div>
      
      <div class="discussion-body">
        <p>{{ discussion.content }}</p>
      </div>

      <div class="discussion-stats">
        <div class="stat-item">
          <el-icon><View /></el-icon>
          <span>{{ discussion.viewNum || 0 }} 浏览</span>
        </div>
        <div class="stat-item">
          <el-icon><ChatLineRound /></el-icon>
          <span>{{ discussion.commentNum || 0 }} 评论</span>
        </div>
      </div>
    </div>

    <!-- 评论区 -->
    <div class="comment-section">
      <h2>评论区</h2>
      
      <!-- 发表评论 -->
      <div class="comment-form" v-if="isLoggedIn">
        <el-input
          v-model="commentContent"
          type="textarea"
          :rows="3"
          placeholder="写下你的评论..."
          maxlength="500"
          show-word-limit
        />
        <div class="comment-form-footer">
          <el-button type="primary" @click="submitComment" :loading="submitting">
            发表评论
          </el-button>
        </div>
      </div>
      <div v-else class="login-tip">
        <el-button type="primary" @click="goToLogin">登录后评论</el-button>
      </div>

      <!-- 评论列表 -->
      <div class="comment-list" v-loading="commentsLoading">
        <el-empty v-if="comments.length === 0" description="暂无评论" />
        
        <div v-else v-for="comment in comments" :key="comment.id" class="comment-item">
          <div class="comment-user">
            <el-avatar :src="comment.avatar || defaultAvatar" :size="32"></el-avatar>
            <div class="comment-user-info">
              <span class="username">{{ comment.author }}</span>
              <span class="role-tag" v-if="comment.role === 1">教师</span>
              <span class="role-tag" v-else-if="comment.role === 2">管理员</span>
              <span class="time">{{ formatTime(comment.createTime) }}</span>
            </div>
          </div>
          
          <div class="comment-content">
            <template v-if="comment.toName">
              回复 <span class="reply-to">@{{ comment.toName }}</span>：
            </template>
            {{ comment.content }}
          </div>

          <div class="comment-actions">
            <el-button
              type="text"
              @click="showReplyInput(comment)"
            >
              回复
            </el-button>
            <el-button
              v-if="canDeleteComment(comment)"
              type="text"
              class="delete-btn"
              @click="deleteComment(comment.id)"
            >
              删除
            </el-button>
          </div>

          <!-- 回复输入框 -->
          <div v-if="replyTo === comment.id" class="reply-input">
            <el-input
              v-model="replyContent"
              type="textarea"
              :rows="2"
              placeholder="写下你的回复..."
              maxlength="200"
              show-word-limit
            />
            <div class="reply-input-footer">
              <el-button size="small" @click="cancelReply">取消</el-button>
              <el-button size="small" type="primary" @click="submitReply(comment)" :loading="submitting">
                回复
              </el-button>
            </div>
          </div>
        </div>

        <!-- 分页 -->
        <div class="pagination-container" v-if="total > 0">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 30, 50]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { View, ChatLineRound, Star, StarFilled } from '@element-plus/icons-vue';
import { useUserStore } from '../store/user';
import {
  getDiscussionDetail,
  likeDiscussion,
  unlikeDiscussion,
  collectDiscussion,
  uncollectDiscussion,
  getCollectionStatus,
  deleteDiscussion
} from '../api/discussion';
import {
  sendComment,
  fetchCommentList,
  deleteComment as deleteCommentApi,
  sendCommentReply,
  fetchCommentReplyList,
  deleteCommentReply
} from '../api/comment';

// 替换默认头像为网络图片
const defaultAvatar = 'https://img1.baidu.com/it/u=1618033988,3141592653&fm=253&fmt=auto&app=138&f=JPEG?w=200&h=200';

// 题目评论区组件，接收props.problemId，显示和操作该题目的评论
const props = defineProps<{ problemId: number }>();
const router = useRouter();
const userStore = useUserStore();

// 状态
const loading = ref(false);
const commentsLoading = ref(false);
const submitting = ref(false);
const discussion = ref<any>({});
const comments = ref<any[]>([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const isLiked = ref(false);
const isCollected = ref(false);
const commentContent = ref('');
const replyContent = ref('');
const replyTo = ref<number | null>(null);

// 计算属性
const isLoggedIn = computed(() => userStore.isLoggedIn);
const currentUserId = computed(() => userStore.userInfo?.id);

// 获取讨论详情
const fetchDiscussion = async () => {
  loading.value = true;
  try {
    const id = Number(props.problemId);
    const result = await getDiscussionDetail(id);
    if (result.code === 0) {
      discussion.value = result.data;
      if (isLoggedIn.value) {
        await checkCollectionStatus();
      }
    } else {
      ElMessage.error(result.msg || '获取讨论详情失败');
    }
  } catch (error) {
    console.error('获取讨论详情失败:', error);
    ElMessage.error('获取讨论详情失败');
  } finally {
    loading.value = false;
  }
};

// 获取评论列表
const fetchComments = async () => {
  commentsLoading.value = true;
  try {
    const result = await fetchCommentList({
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      toPid: props.problemId.toString(),
      sortBy: 'create_time',
      orderBy: 'desc'
    });
    
    if (result.code === 0) {
      comments.value = result.data.records || [];
      total.value = result.data.total || 0;
    } else {
      ElMessage.error(result.msg || '获取评论列表失败');
    }
  } catch (error) {
    console.error('获取评论列表失败:', error);
    ElMessage.error('获取评论列表失败');
  } finally {
    commentsLoading.value = false;
  }
};

// 检查收藏状态
const checkCollectionStatus = async () => {
  try {
    const id = Number(props.problemId);
    const result = await getCollectionStatus(id);
    if (result.code === 0) {
      isCollected.value = result.data;
    }
  } catch (error) {
    console.error('获取收藏状态失败:', error);
  }
};

// 处理点赞
const handleLike = async () => {
  if (!isLoggedIn.value) {
    ElMessage.warning('请先登录');
    router.push('/login');
    return;
  }

  try {
    const id = Number(props.problemId);
    const result = await (isLiked.value ? unlikeDiscussion(id) : likeDiscussion(id));
    
    if (result.code === 0) {
      isLiked.value = !isLiked.value;
      discussion.value.likeNum = (discussion.value.likeNum || 0) + (isLiked.value ? 1 : -1);
      ElMessage.success(isLiked.value ? '点赞成功' : '取消点赞成功');
    } else {
      ElMessage.error(result.msg || '操作失败');
    }
  } catch (error) {
    console.error('点赞操作失败:', error);
    ElMessage.error('操作失败，请稍后重试');
  }
};

// 处理收藏
const handleCollect = async () => {
  if (!isLoggedIn.value) {
    ElMessage.warning('请先登录');
    router.push('/login');
    return;
  }

  try {
    const id = Number(props.problemId);
    const result = await (isCollected.value ? uncollectDiscussion(id) : collectDiscussion(id));
    
    if (result.code === 0) {
      isCollected.value = !isCollected.value;
      ElMessage.success(isCollected.value ? '收藏成功' : '取消收藏成功');
    } else {
      ElMessage.error(result.msg || '操作失败');
    }
  } catch (error) {
    console.error('收藏操作失败:', error);
    ElMessage.error('操作失败，请稍后重试');
  }
};

// 处理删除
const handleDelete = async () => {
  try {
    await ElMessageBox.confirm('确定要删除这条讨论吗？', '提示', {
      type: 'warning'
    });
    
    const id = Number(props.problemId);
    const result = await deleteDiscussion(id);
    
    if (result.code === 0) {
      ElMessage.success('删除成功');
      router.push('/discussions');
    } else {
      ElMessage.error(result.msg || '删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除讨论失败:', error);
      ElMessage.error('删除失败，请稍后重试');
    }
  }
};

// 提交评论
const submitComment = async () => {
  if (!commentContent.value.trim()) {
    ElMessage.warning('请输入评论内容');
    return;
  }

  submitting.value = true;
  try {
    const result = await sendComment({
      content: commentContent.value,
      toPid: props.problemId
    });
    
    if (result.code === 0) {
      ElMessage.success('评论成功');
      commentContent.value = '';
      await fetchComments();
      discussion.value.commentNum = (discussion.value.commentNum || 0) + 1;
    } else {
      ElMessage.error(result.msg || '评论失败');
    }
  } catch (error) {
    console.error('发表评论失败:', error);
    ElMessage.error('评论失败，请稍后重试');
  } finally {
    submitting.value = false;
  }
};

// 显示回复输入框
const showReplyInput = (comment: any) => {
  if (!isLoggedIn.value) {
    ElMessage.warning('请先登录');
    router.push('/login');
    return;
  }
  replyTo.value = comment.id;
  replyContent.value = '';
};

// 取消回复
const cancelReply = () => {
  replyTo.value = null;
  replyContent.value = '';
};

// 提交回复
const submitReply = async (comment: any) => {
  if (!replyContent.value.trim()) {
    ElMessage.warning('请输入回复内容');
    return;
  }

  submitting.value = true;
  try {
    const result = await sendCommentReply({
      content: replyContent.value,
      toCid: comment.id,
      toName: comment.author,
      toPid: props.problemId
    });
    
    if (result.code === 0) {
      ElMessage.success('回复成功');
      replyContent.value = '';
      replyTo.value = null;
      await fetchComments();
      discussion.value.commentNum = (discussion.value.commentNum || 0) + 1;
    } else {
      ElMessage.error(result.msg || '回复失败');
    }
  } catch (error) {
    console.error('发表回复失败:', error);
    ElMessage.error('回复失败，请稍后重试');
  } finally {
    submitting.value = false;
  }
};

// 删除评论
const deleteComment = async (commentId: number) => {
  try {
    await ElMessageBox.confirm('确定要删除这条评论吗？', '提示', {
      type: 'warning'
    });
    
    const result = await deleteCommentApi(commentId);
    
    if (result.code === 0) {
      ElMessage.success('删除成功');
      await fetchComments();
      discussion.value.commentNum = Math.max(0, (discussion.value.commentNum || 0) - 1);
    } else {
      ElMessage.error(result.msg || '删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除评论失败:', error);
      ElMessage.error('删除失败，请稍后重试');
    }
  }
};

// 判断是否可以删除评论
const canDeleteComment = (comment: any) => {
  return isLoggedIn.value && (currentUserId.value === comment.uid);
};

// 处理分页
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  fetchComments();
};

const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  fetchComments();
};

// 格式化时间
const formatTime = (time: string) => {
  if (!time) return '';
  const date = new Date(time);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  });
};

// 跳转到登录页
const goToLogin = () => {
  router.push('/login');
};

// 组件挂载时获取数据
onMounted(() => {
  fetchDiscussion();
  fetchComments();
});
</script>

<style scoped>
.problem-comments {
  width: 100%;
}

.discussion-content {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.discussion-header {
  margin-bottom: 20px;
}

.discussion-header h1 {
  margin: 0 0 20px 0;
  font-size: 24px;
  color: #303133;
}

.discussion-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.user-info {
  display: flex;
  align-items: center;
}

.author-info {
  margin-left: 10px;
  display: flex;
  flex-direction: column;
}

.author-name {
  font-weight: 600;
  color: #303133;
}

.role-tag {
  background-color: #409eff;
  color: white;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
  margin-left: 8px;
}

.create-time {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.discussion-body {
  margin: 20px 0;
  line-height: 1.6;
  color: #303133;
}

.discussion-stats {
  display: flex;
  gap: 20px;
  color: #909399;
  font-size: 14px;
}

.stat-item {
  display: flex;
  align-items: center;
}

.stat-item .el-icon {
  margin-right: 5px;
}

.comment-section {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.comment-section h2 {
  margin: 0 0 20px 0;
  font-size: 20px;
  color: #303133;
}

.comment-form {
  margin-bottom: 30px;
}

.comment-form-footer {
  margin-top: 10px;
  display: flex;
  justify-content: flex-end;
}

.login-tip {
  text-align: center;
  padding: 20px;
  color: #909399;
}

.comment-list {
  margin-top: 20px;
}

.comment-item {
  padding: 15px 0;
  border-bottom: 1px solid #ebeef5;
}

.comment-item:last-child {
  border-bottom: none;
}

.comment-user {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.comment-user-info {
  margin-left: 10px;
  display: flex;
  align-items: center;
}

.username {
  font-weight: 500;
  color: #303133;
}

.time {
  font-size: 12px;
  color: #909399;
  margin-left: 10px;
}

.comment-content {
  margin: 10px 0;
  line-height: 1.6;
  color: #606266;
}

.reply-to {
  color: #409eff;
  font-weight: 500;
}

.comment-actions {
  display: flex;
  gap: 15px;
}

.delete-btn {
  color: #f56c6c;
}

.reply-input {
  margin-top: 10px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.reply-input-footer {
  margin-top: 10px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style> 